import { Button, Card, Form, Input, Pagination, Space, Table, Tag } from "antd";
import { useEffect, useState } from "react";
import { getPaperList, togglePaperVideoStatus } from "../../api/paper";
import type { TableProps } from 'antd';

const PaperPage = () => {

  const defaultParams = { id: '', paperName: '', pageNo: 1, pageSize: 10 }
  const [params, setParams] = useState(defaultParams)
  const [list, setList] = useState<Paper[]>([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)

  const getList = async () => {
    setLoading(true)
    try {
      const r = await getPaperList(params)
      setList(r.data.records)
      setTotal(r.data.total)
    } catch (error) {
      console.log(error)
    } finally {
      setLoading(false)
    }
  }

  const search = (values: typeof defaultParams) => {
    setParams(values)
  }

  const toggleVideoStatus = async (row: Paper, index: number) => {
    const prev = row.videoStatus
    const status = prev == 0 ? 1 : 0
    // 乐观更新状态
    const newList = list.slice()
    newList[index].videoStatus = status
    setList(newList)
    // 走真正的接口更新数据
    const r: any = await togglePaperVideoStatus(row.id, status)
    if (r.code != 0) {
      // 失败的时候就还原成之前的状态
      row.videoStatus = prev
    }
  }

  const onPaginationChange = (page: number, pageSize: number) => {
    setParams({ ...params, pageNo: page, pageSize })
  }

  const columns: TableProps<Paper>['columns'] = [
    {
      dataIndex: 'id',
      title: '试卷id',
      key: 'id'
    },
    {
      dataIndex: 'paperName',
      title: '试卷名称',
      key: 'paperName'
    },
    {
      dataIndex: 'subjectDTO.name',
      title: '科目',
      key: 'subjectDTO.name',
      render: (_, { subjectDTO }) => <span>{ subjectDTO?.name }</span>
    },
    {
      dataIndex: 'phaseDTO.phaseName',
      title: '学段',
      key: 'phaseDTO.phaseName',
      render: (_, { phaseDTO }) => <span>{ phaseDTO?.phaseName }</span>
    },
    {
      dataIndex: 'status',
      title: '试卷状态',
      key: 'status',
      render(_, record) {
        const color = record.status === 1 ? 'green' : 'red'
        const text = record.status === 1 ? '已审核' : '未审核'
        return <Tag color={color} key={text}>{text}</Tag>
      },
    },
    {
      dataIndex: 'videoStatus',
      title: '视频状态',
      key: 'videoStatus',
      render(_, record) {
        const color = record.videoStatus === 1 ? 'green' : 'red'
        const text = record.videoStatus === 1 ? '已完成' : '未完成'
        return <Tag bordered={false} color={color} key={text}>{text}</Tag>
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, index) => (
        <Space size="middle">
          <a onClick={() => toggleVideoStatus(record, index)}>切换视频状态</a>
        </Space>
      )
    }
  ]

  useEffect(() => {
    getList()
  }, [params])

  return (
    <>
      <Card className="mb-3">
        <Form initialValues={{}} layout="inline" onFinish={search}>
          <Form.Item label="试卷ID" name="id">
            <Input allowClear />
          </Form.Item>
          <Form.Item label="试卷名称" name="paperName">
            <Input allowClear />
          </Form.Item>
          <Form.Item label="">
            <Button htmlType="submit" type="primary">搜索</Button>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table 
          className="mb-3"
          pagination={false} 
          rowKey="id"
          bordered
          loading={loading} 
          columns={columns} 
          dataSource={list} />
        <Pagination
          className="flex justify-end"
          current={params.pageNo}
          pageSize={params.pageSize}
          onChange={onPaginationChange}
          total={total}
          showSizeChanger
          showTotal={(total) => `共 ${total} 条数据`}
        />
      </Card>
    </>
  );
}

export default PaperPage